package com.diudiutechnology.www.yadiudiu.util.utils;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Properties;

public final class FileUtils {

	/**
	 * 覆盖方式写文件
	 *
	 * @param mContext
	 * @param fileName
	 *            如果该文件存在，则覆盖该文件
	 * @param content
	 * @throws IOException
	 */
	public static void write(Context mContext, String fileName, byte[] content)
			throws IOException {
		FileOutputStream fos = null;
		try {
			fos = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
			fos.write(content);
		} finally {
			if (fos != null) {
				fos.close();
				fos = null;
			}
		}
	}

	/**
	 * 覆盖方式写文件 写入对象
	 *
	 * @Title: writeObject
	 * @Description: TODO
	 * @param mContext
	 * @param fileName
	 * @param content
	 * @throws IOException
	 * @return: void
	 */
	public static void writeObject(Context mContext, String fileName,
                                   Object content) throws IOException {
		FileOutputStream fos = null;
		try {
			fos = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(content);
		} finally {
			if (fos != null) {
				fos.close();
				fos = null;
			}
		}
	}

	/**
	 * 拷贝文件到内部存储
	 *
	 * @Title: copyApkFromAssets
	 * @Description: TODO
	 * @param context
	 * @param fileName
	 * @return
	 * @return: boolean
	 */
	public static boolean copyApkFromAssets(Context context, String fileName) {
		boolean copyIsFinish = false;
		try {
			InputStream is = context.getAssets().open(fileName);
			FileOutputStream fos = context.openFileOutput(fileName,
					Context.MODE_PRIVATE);
			byte[] temp = new byte[1024];
			int i = 0;
			while ((i = is.read(temp)) > 0) {
				fos.write(temp, 0, i);
			}
			fos.close();
			is.close();
			copyIsFinish = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return copyIsFinish;
	}

	/**
	 * 追加方式写文件
	 *
	 * @param mContext
	 * @param fileName
	 * @param content
	 * @throws IOException
	 */
	public static void writeWithAppend(Context mContext, String fileName,
                                       byte[] content) throws IOException {
		FileOutputStream fos = null;
		try {
			fos = mContext.openFileOutput(fileName, Context.MODE_APPEND);
			fos.write(content);
		} finally {
			if (fos != null) {
				fos.close();
				fos = null;
			}
		}
	}

	/**
	 * 读取文件
	 *
	 * @param mContext
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static byte[] read(Context mContext, String fileName)
			throws IOException {
		FileInputStream fis = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] result = null;
		try {
			int len = 1024;
			byte[] buffer = new byte[len];
			fis = mContext.openFileInput(fileName);
			int nrb = fis.read(buffer, 0, len); // read up to len bytes
			while (nrb != -1) {
				baos.write(buffer, 0, nrb);
				nrb = fis.read(buffer, 0, len);
			}
			result = baos.toByteArray();
			baos.close();
		} finally {
			if (fis != null) {
				fis.close();
				fis = null;
			}
		}
		return result;
	}

	/**
	 * 读取文件 对象
	 *
	 * @Title: readObject
	 * @Description: TODO
	 * @param mContext
	 * @param fileName
	 * @return
	 * @throws IOException
	 * @return: Object
	 */
	public static Object readObject(Context mContext, String fileName)
			throws IOException {
		FileInputStream fis = null;
		Object obj = null;
		try {
			fis = mContext.openFileInput(fileName);
			ObjectInputStream ois = new ObjectInputStream(fis);
			obj = ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				fis.close();
				fis = null;
			}
		}
		return obj;
	}

	/**
	 * 删除文件
	 *
	 * @param mContext
	 * @param fileName
	 */
	public static void delete(Context mContext, String fileName) {
		File file = mContext.getFileStreamPath(fileName);
		if (file != null) {
			file.delete();
		}
	}

	/**
	 * 文件是否存在
	 *
	 * @param mContext
	 * @param fileName
	 * @return
	 */
	public static boolean isFileExist(Context mContext, String fileName) {
		File file = mContext.getFileStreamPath(fileName);
		if (file != null && file.exists()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取文件
	 *
	 * @Title: createFileIfnotExist
	 * @Description: TODO
	 * @param mContext
	 * @param fileName
	 * @return
	 * @return: File
	 */
	public static File getFileWithPath(Context mContext, String fileName) {
		File file = mContext.getFileStreamPath(fileName);
		if (file == null || !file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	/**
	 * 获取assets文件
	 */
	public static String getFromAssets(Context context, String fileName) {
		String result = "";
		try {
			InputStreamReader inputReader = new InputStreamReader(context
					.getAssets().open(fileName));
			BufferedReader bufReader = new BufferedReader(inputReader);
			String line = "";
			while ((line = bufReader.readLine()) != null)
				result += line;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取配置文件
	 */
	public static String getProperties(Context context, String fileName,
                                       String s) {
		String result = "";
		Properties properties = new Properties();
		try {
			properties.load(context.getAssets().open(fileName));
			result = new String(properties.getProperty(s)
					.getBytes("ISO-8859-1"), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result == null ? "" : result;
	}

	public static String getSavePath(int type) {
		String path;
		String floder = (type == Constant.FILE_SAVE_TYPE_IMAGE) ? "images"
				: "audio";
		if (FileUtils.checkSDCard()) {
			path = Environment.getExternalStorageDirectory().toString()
					+ File.separator + "MGJ-IM" + File.separator + floder
					+ File.separator;

		} else {
			path = Environment.getDataDirectory().toString() + File.separator
					+ "MGJ-IM" + File.separator + floder + File.separator;
		}
		return path;
	}

	/**
	 * @Description 判断存储卡是否存在
	 * @return
	 */
	public static boolean checkSDCard() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		}

		return false;
	}
	public static boolean hasSd() {
		return Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState());
	}

	/**
	 *
	 * @return
	 */
	public static Uri getTempUri() {
		return Uri.fromFile(getTempFile());
	}
	public static final String IMAGE_TEMP_DIR = "/leaves/temp/";
	public static String IMAGE_TEMP_PATH = Environment.getExternalStorageDirectory().getPath() + IMAGE_TEMP_DIR;
	public static File getTempFile() {
		if (hasSd()) {
			File temp = new File(IMAGE_TEMP_PATH);
			if (!temp.exists()) {
				temp.mkdirs();
			}
			String path = IMAGE_TEMP_PATH + System.currentTimeMillis() + ".png";
			File file = new File(path);
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return file;
		}
		return null;
	}

	/**
	 * 删除单个文件
	 * @param   filePath    被删除文件的文件名
	 * @return 文件删除成功返回true，否则返回false
	 */
	public static boolean deleteFile(String filePath) {
		File file = new File(filePath);
		if (file.isFile() && file.exists()) {
			return file.delete();
		}
		return false;
	}

	/**
	 * 删除文件夹以及目录下的文件
	 * @param   filePath 被删除目录的文件路径
	 * @return  目录删除成功返回true，否则返回false
	 */
	public static boolean deleteDirectory(String filePath) {
		boolean flag = false;
		//如果filePath不以文件分隔符结尾，自动添加文件分隔符
		if (!filePath.endsWith(File.separator)) {
			filePath = filePath + File.separator;
		}
		File dirFile = new File(filePath);
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		flag = true;
		File[] files = dirFile.listFiles();
		//遍历删除文件夹下的所有文件(包括子目录)
		for (int i = 0; i < files.length; i++) {
			if (files[i].isFile()) {
				//删除子文件
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag) break;
			} else {
				//删除子目录
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag) break;
			}
		}
		if (!flag) return false;
		//删除当前空目录
		return dirFile.delete();
	}

	/**
	 *  根据路径删除指定的目录或文件，无论存在与否
	 *@param filePath  要删除的目录或文件
	 *@return 删除成功返回 true，否则返回 false。
	 */
	public static boolean DeleteFolder(String filePath) {
		File file = new File(filePath);
		if (!file.exists()) {
			return false;
		} else {
			if (file.isFile()) {
				// 为文件时调用删除文件方法
				return deleteFile(filePath);
			} else {
				// 为目录时调用删除目录方法
				return deleteDirectory(filePath);
			}
		}
	}
}
